/**
     *
     */

package com.xyz.frame.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.alipay.api.response.AlipayTradeWapPayResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyz.frame.bean.app.param.PayParam;
import com.xyz.frame.bean.enums.PayType;
import com.xyz.frame.bean.event.PaySuccessOrderEvent;
import com.xyz.frame.bean.model.Order;
import com.xyz.frame.bean.model.OrderSettlement;
import com.xyz.frame.bean.pay.PayInfoDto;
import com.xyz.frame.common.exception.XyzShopBindException;
import com.xyz.frame.common.util.Arith;
import com.xyz.frame.dao.OrderMapper;
import com.xyz.frame.dao.OrderSettlementMapper;
import com.xyz.frame.service.PayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.stream.Collectors;

/**
 *  on 2018/09/15.
 */
@Service
@Slf4j
public class PayServiceImpl implements PayService {

    @Autowired
    private OrderMapper orderMapper;



    @Autowired
    private OrderSettlementMapper orderSettlementMapper;


    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @Autowired
    private Snowflake snowflake;

    /**
     * 不同的订单号，同一个支付流水号
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayInfoDto pay(String userId, PayParam payParam) {


        // 不同的订单号的产品名称
        StringBuilder prodName = new StringBuilder();
        // 支付单号
        String payNo = String.valueOf(snowflake.nextId());
        String[] orderNumbers = payParam.getOrderNumbers().split(StrUtil.COMMA);
        // 修改订单信息
        for (String orderNumber : orderNumbers) {
            OrderSettlement orderSettlement = new OrderSettlement();
            orderSettlement.setPayNo(payNo);
            orderSettlement.setPayType(payParam.getPayType());
            orderSettlement.setUserId(userId);
            orderSettlement.setOrderNumber(orderNumber);
            orderSettlementMapper.updateByOrderNumberAndUserId(orderSettlement);

            Order order = orderMapper.getOrderByOrderNumber(orderNumber);
            prodName.append(order.getProdName()).append(StrUtil.COMMA);
        }
        // 除了ordernumber不一样，其他都一样
        List<OrderSettlement> settlements = orderSettlementMapper.getSettlementsByPayNo(payNo);
        // 应支付的总金额
        double payAmount = 0.0;
        for (OrderSettlement orderSettlement : settlements) {
            payAmount = Arith.add(payAmount, orderSettlement.getPayAmount());
        }

        prodName.substring(0, Math.min(100, prodName.length() - 1));

        PayInfoDto payInfoDto = new PayInfoDto();
        payInfoDto.setBody(prodName.toString());
        payInfoDto.setPayAmount(payAmount);
        payInfoDto.setPayNo(payNo);
        return payInfoDto;
    }

    /**
     * 无订单的支付
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public PayInfoDto noOrderPay(String userId, PayParam payParam) {
        // 支付单号
        String payNo = String.valueOf(snowflake.nextId());
        Object url = null;
        try {
            url = onPaymentByAlipay(payNo, new BigDecimal(payParam.getMoney()).setScale(2, RoundingMode.HALF_UP), userId);
        } catch (Exception e) {
            e.printStackTrace();
        }

        PayInfoDto payInfoDto = new PayInfoDto();
        payInfoDto.setBody(String.valueOf(url));
        payInfoDto.setPayAmount(30.00);
        payInfoDto.setPayNo(payNo);
        return payInfoDto;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> paySuccess(String payNo, String bizPayNo) {
        List<OrderSettlement> orderSettlements = orderSettlementMapper.selectList(new LambdaQueryWrapper<OrderSettlement>().eq(OrderSettlement::getPayNo, payNo));

        OrderSettlement settlement = orderSettlements.get(0);

        // 订单已支付
        if (settlement.getPayStatus() == 1) {
            throw new XyzShopBindException("订单已支付");
        }
        // 修改订单结算信息
        if (orderSettlementMapper.updateToPay(payNo, settlement.getVersion()) < 1) {
            throw new XyzShopBindException("结算信息已更改");
        }


        List<String> orderNumbers = orderSettlements.stream().map(OrderSettlement::getOrderNumber).collect(Collectors.toList());

        // 将订单改为已支付状态
        orderMapper.updateByToPaySuccess(orderNumbers, PayType.WECHATPAY.value());

        List<Order> orders = orderNumbers.stream().map(orderNumber -> orderMapper.getOrderByOrderNumber(orderNumber)).collect(Collectors.toList());
        eventPublisher.publishEvent(new PaySuccessOrderEvent(orders));
        return orderNumbers;
    }


    /**
     * 支付宝支付
     * @return
     */
    public Object onPaymentByAlipay(String tradeNo, BigDecimal onlineMoney,
                                    String userId) throws Exception{
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipay.com/gateway.do",
                "2021005165696560",
                "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCI+EFWJ0o0L3m7e2bJUDKFjI4bzPkyQEg3cOHXSf6LA76/eC3Kbp5ePnYrigrjE0l7jAK8406iz3R2VAXwyG4dP+iZhvVkyX4YsVF197chDpHDQlPHkOzhV8/YbJQ1mq3r9VIDPLRP7a34txSB46GG1vAdfAsJQtPT6Z3njKux24Lb650NXq+dgZEaCPZ3GU11f6BzlfxjYFDHQ1j1IMgRTNGe4EhmxruK39GA6gDxZEo9C3Q4Y+VvnEGUakrHiW/G2sCUtyWtuEx7PmyPoBwqYmlRHPMPQBX4PSi/ALQ1U667XAiQgGSN7nw5jowb8Jzq5eBn+JMRganbZTY2X9P/AgMBAAECggEAaDp6BaRqXCHQgbGa+xCTEXtu3IrzCqFOExpMUXbWQ1T7P1qlhcj9rHvdkq4+MKQJpAFcR/61ZUF2v2CbEKqE2K88QjAn5qVJ1mKAucNiUL50f2CmvlNzXttip6+gbNYjCU6qNRppn/UfEQfIjDr7PM+s8tLk1wxKg5Tf+0bZlMJ3sEzeZJ74XJF1Ehnt1ZeUbj/vjP82nQ7U8NiTE0uBaGdsqphyDOZF+PKjwxA3cEltm/oXL7JOUhH2jmecj/N8lSDVHQ8d1OkDdxYDeVje8yz9G3g/xMLkHV0X+TNrMpVkoc/pCDToUmaM16/GUH5v1zw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WYph1l/sQ66PxTentcDueQyWs7yjqs9bqL/Wm//qKOrGJ/RQJK8LETFIPj+QDpUJIv5AqOWWTOkpLiImNlTDCWNlzt/Yx03uaL9SaxfJ9BZ3nMN0L4vbYm+q0HEmNvdlm2I4MknxT3mvgHy7rK9ZexEk3Qre7owYAAQi2EiBPr2VR074Rto+kpPvUumwZaWvxtM+ve9TO+OFl4QSZ966Ig9CuU8LMNcH47/cpQIDAQAB",
                "RSA2"
        );
        AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
        request.setNotifyUrl("https://120.26.8.233:8086/api/p/order/noOrderPayAlipayNotify?userId="+userId);
        request.setReturnUrl("https://120.26.8.233:8086/api/p/order/noOrderPayAlipayReturn?userId="+userId);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", tradeNo);
        bizContent.put("total_amount", onlineMoney);
        bizContent.put("subject", "订单支付");
        bizContent.put("product_code", "QUICK_WAP_WAY");

        log.info("===>onPaymentByAlipay=>bizContent:{}",bizContent);
        request.setBizContent(bizContent.toString());
        log.info("===>onPaymentByAlipay=>request:{}",JSONObject.toJSONString(request));

//        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
        AlipayTradeWapPayResponse response = alipayClient.pageExecute(request,"GET");
        log.info("===>onPaymentByAlipay=>response:{}",JSONObject.toJSONString(response));
        if(response.isSuccess()){
            System.out.println("调用成功");
            log.info("生成的支付宝支付URL: {}", response.getBody());
        } else {
            System.out.println("调用失败");
            return null;
        }
        return response.getBody();
    }
}
